package com.aidex.web.controller.biz;

import com.aidex.biz.domain.JdkyOrder;
import com.aidex.biz.domain.Order;
import com.aidex.biz.domain.vo.OrderExport;
import com.aidex.biz.service.*;
import com.aidex.common.annotation.Log;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.aidex.system.service.CompanyService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersCreateLopResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单Controller
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-10-12
 */
@RestController
@RequestMapping("/biz/bizOrder")
public class OrderController extends BaseController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AccountInfoService accountInfoService;
    @Autowired
    private OrderAccountInfoService orderAccountInfoService;
    @Autowired
    private AccountLogService accountLogService;
    @Autowired
    private AccountTypeService accountTypeService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SmSSendService smSSendService;

    @Autowired
    private QingYangOrderService qingYangOrderService;

    @Autowired
    private JdKuaiyunService jdKuaiyunService;

    @Autowired
    private JdkyOrderService jdkyOrderService;


    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizOrder:list')")
    @GetMapping("/list")
    public R<PageInfo> list(Order order, HttpServletRequest request, HttpServletResponse response) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            order.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        if ("3".equals(order.getStatus())) {
            order.setStatus("0");
        }
        if ("4".equals(order.getStatus())) {
            order.setStatus("2");
        }
        if ("5".equals(order.getStatus())) {
            order.setStatus("0");
        }
        if ("6".equals(order.getStatus())) {
            order.setStatus("2");
        }

        order.setPage(new PageDomain(request, response));
        order.getPage().setIsAsc(order.getOrder());
        return R.data(orderService.findPage(order));
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizOrder:query')")
    @GetMapping(value = "/{id}")
    public R<Order> detail(@PathVariable("id") String id) {
        return R.data(orderService.get(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('biz:bizOrder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated Order order) {
        return R.status(orderService.save(order));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('biz:bizOrder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated Order order) {
        return R.status(orderService.save(order));
    }


    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('biz:bizOrder:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(orderService.deleteOrderByIds(ids));
    }

    /**
     * 获取最大编号
     */
    @PreAuthorize("@ss.hasPermi('biz:bizOrder:query')")
    @GetMapping("/findMaxSort")
    public R findMaxSort() {
        return R.data(orderService.findMaxSort(new Order()));
    }

    /**
     * 导出订单列表
     */

    @Log(title = "导出订单列表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(Order order) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            order.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        if ("3".equals(order.getStatus())) {
            order.setStatus("0");
        }
        if ("4".equals(order.getStatus())) {
            order.setStatus("2");
        }
        if ("5".equals(order.getStatus())) {
            order.setStatus("0");
        }
        if ("6".equals(order.getStatus())) {
            order.setStatus("2");
        }
        List<OrderExport> list=new ArrayList<>();//orderService.exportOrder(order);
        ExcelUtil<OrderExport> util = new ExcelUtil<OrderExport>(OrderExport.class);
        return util.exportExcel(list, "-导出时间：" + StringUtils.getStringDate() + "分拣订单数据");
    }

    /**
     * 支付订单金额到用户账户 线上
     */
//    @Log(title = "支付订单金额到用户账户", businessType = BusinessType.OTHER)
//    @PostMapping("/paytoUser")
//    public R paytoUser(@RequestBody Order order) {
//        return R.status(orderService.payToUser(order, "y"));
//    }

    /**
     * 线下支付订单金额
     */
//    @Log(title = "线下支付订单金额", businessType = BusinessType.OTHER)
//    @PostMapping("/xianxiaPaytoUser")
//    public R xianxiaPaytoUser(@RequestBody Order order) {
//        order = orderService.get(order.getOrderId());
//
//        return R.status(orderService.payToUser(order, "n"));
//    }


    /**
     * 批量打款订单 线上
     */
//    @Log(title = "批量打款订单", businessType = BusinessType.OTHER)
//    @PostMapping("/batchPaytoUser")
//    public R batchPaytoUser(@RequestBody @Validated List<Order> orders) {
//        for (Order order : orders) {
//            orderService.payToUser(order, "y");
//        }
//        return R.status(true);
//    }

    /**
     * 批量打款订单 线下
     */
//    @Log(title = "批量打款订单", businessType = BusinessType.OTHER)
//    @PostMapping("/xianxiabatchPaytoUser")
//    public R xianxiabatchPaytoUser(@RequestBody @Validated List<Order> orders) {
//        for (Order order : orders) {
//            orderService.payToUser(order, "n");
//        }
//        return R.status(true);
//    }


    /**
     * 获取用户所有投递订单金额
     */
//    @Log(title = "获取用户所有投递订单金额", businessType = BusinessType.OTHER)
//    @GetMapping("/getAllOrderAmount")
//    public R getAllOrderAmount(Order order) {
//        return R.data(orderService.getAllOrderAmountByUserInfoId(order.getUserInfoId()));
//    }


    @GetMapping("/pushOrder")
    public R pushOrder(Order order) throws Exception {
        order=orderService.get(order.getId());
        JSONObject qyJsonObject= qingYangOrderService.pushQingYangOrder(order);
        if("200".equals(qyJsonObject.getString("code"))){
            order.setQingyangOrderId(qyJsonObject.getJSONObject("data").getString("qingyangOrderNumber"));
        }
        return R.data(orderService.save(order));
    }

    /**
     * 推送到京东快运
     * @param order
     * @return
     * @throws Exception
     */
    @GetMapping("/pushJdKuaiYun")
    public R pushJdKuaiYun(Order order) throws Exception {
        order=orderService.get(order.getId());
        // 平台订单推送到京东快递
        if(AiDexConfig.getCompanyId().equals(order.getCompanyId())){
            EcapV1OrdersCreateLopResponse ecapV1OrdersCreateLopResponse= jdKuaiyunService.sendJdKuaiYuanOrder(order);
            JdkyOrder jdkyOrder=new JdkyOrder();
            jdkyOrder.setOrderId(order.getId());
            if("0".equals(ecapV1OrdersCreateLopResponse.getCode())){
                order.setDeliveryNo(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
                jdkyOrder.setOrderCode(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
                jdkyOrder.setStatus("1");
                // 修改轻氧运单号
                JSONObject jsonObject=qingYangOrderService.modifyDeliveryNumber(order);
                if("200".equals(jsonObject.getString("code"))){
                    jdkyOrder.setStatus("2");
                    jdkyOrder.setRemark("京东快运订单推送成功！");
                }else{
                    jdkyOrder.setRemark(jsonObject.toString());
                }

            }else{
                jdkyOrder.setStatus("0");
                jdkyOrder.setRemark(ecapV1OrdersCreateLopResponse.getMsg());

            }
            jdkyOrderService.save(jdkyOrder);
        }
        return R.status(orderService.save(order));
    }


}
